package com.tzh.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;

@Aspect
@Component
public class ConrtollerLogAspect {

    private final static Logger logger = LoggerFactory.getLogger(ConrtollerLogAspect.class);

    // ..表示包及子包 该方法代表controller层的所有方法
    @Pointcut("execution(public * com.tzh.controller.*.*(..))")
    public void PlginMethod() {
    }

    @Before("PlginMethod()")
    public void LogRequestInfo(JoinPoint joinPoint) throws Exception {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        StringBuffer requestLog = new StringBuffer();
        requestLog.append("请求信息：")
                .append("URL = {" + request.getRequestURI() + "},\t")
                .append("HTTP_METHOD = {" + request.getMethod() + "},\t")
                .append("IP = {" + request.getRemoteAddr() + "},\t")
                .append("CLASS_METHOD = {" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + "},\t\n").append("Header=");
        List<String> list = Collections.list(request.getHeaderNames());
        list.forEach(key -> {
            requestLog.append("[").append(key + "=" + request.getHeader(key)).append("],");
        });
        logger.info(requestLog.toString());
    }

    @AfterReturning(returning = "resultVO", pointcut = "PlginMethod()")
    public void logResultVOInfo(Object resultVO) throws Exception {
//	        logger.info("请求结果：" + resultVO.toString());

    }

}
